/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

/**
 * 工具函数库
 * 提供通用的工具函数，包括错误处理、加载状态、Toast提示等
 */

// Toast 提示
function showToast(message, type = 'info', duration = 3000) {
    // 移除已存在的 toast
    const existingToast = document.getElementById('global-toast');
    if (existingToast) {
        existingToast.remove();
    }

    const toast = document.createElement('div');
    toast.id = 'global-toast';
    toast.style.cssText = `
        position: fixed;
        top: 20px;
        left: 50%;
        transform: translateX(-50%);
        background-color: ${type === 'error' ? '#f44336' : type === 'success' ? '#4caf50' : '#2196f3'};
        color: white;
        padding: 12px 24px;
        border-radius: 6px;
        box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        z-index: 10000;
        font-size: 14px;
        max-width: 80%;
        text-align: center;
        animation: slideDown 0.3s ease-out;
    `;
    toast.textContent = message;

    // 添加动画样式
    if (!document.getElementById('toast-styles')) {
        const style = document.createElement('style');
        style.id = 'toast-styles';
        style.textContent = `
            @keyframes slideDown {
                from {
                    opacity: 0;
                    transform: translateX(-50%) translateY(-20px);
                }
                to {
                    opacity: 1;
                    transform: translateX(-50%) translateY(0);
                }
            }
        `;
        document.head.appendChild(style);
    }

    document.body.appendChild(toast);

    setTimeout(() => {
        toast.style.opacity = '0';
        toast.style.transition = 'opacity 0.3s';
        setTimeout(() => {
            if (toast.parentNode) {
                toast.parentNode.removeChild(toast);
            }
        }, 300);
    }, duration);
}

// 显示加载状态
function showLoading(containerId, message = '加载中...') {
    const container = document.getElementById(containerId);
    if (!container) return;

    const loading = document.createElement('div');
    loading.className = 'loading-indicator';
    loading.id = containerId + '-loading';
    loading.style.cssText = `
        text-align: center;
        padding: 20px;
        color: #666;
    `;
    loading.innerHTML = `
        <div style="display: inline-block; width: 20px; height: 20px; border: 3px solid #f3f3f3; border-top: 3px solid #3498db; border-radius: 50%; animation: spin 1s linear infinite;"></div>
        <p style="margin-top: 10px; margin-bottom: 0;">${message}</p>
    `;

    // 添加旋转动画
    if (!document.getElementById('loading-styles')) {
        const style = document.createElement('style');
        style.id = 'loading-styles';
        style.textContent = `
            @keyframes spin {
                0% { transform: rotate(0deg); }
                100% { transform: rotate(360deg); }
            }
        `;
        document.head.appendChild(style);
    }

    container.innerHTML = '';
    container.appendChild(loading);
}

// 隐藏加载状态
function hideLoading(containerId) {
    const loading = document.getElementById(containerId + '-loading');
    if (loading && loading.parentNode) {
        loading.parentNode.removeChild(loading);
    }
}

// 显示错误信息
function showError(containerId, message) {
    const container = document.getElementById(containerId);
    if (!container) return;

    const errorDiv = document.createElement('div');
    errorDiv.className = 'error-message';
    errorDiv.style.cssText = `
        background-color: #fee;
        color: #c00;
        padding: 15px;
        border-radius: 6px;
        border-left: 4px solid #f00;
        margin-top: 20px;
    `;
    errorDiv.innerHTML = `
        <p style="margin: 0; font-weight: bold;">错误</p>
        <p style="margin: 5px 0 0 0;">${message}</p>
    `;

    container.innerHTML = '';
    container.appendChild(errorDiv);
}

// 格式化日期时间
function formatDateTime(timestamp) {
    if (!timestamp || timestamp <= 0) {
        return '未知';
    }
    
    const ts = timestamp > 1000000000000 ? timestamp : timestamp * 1000;
    return new Date(ts).toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
    });
}

// 防抖函数
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// 节流函数
function throttle(func, limit) {
    let inThrottle;
    return function(...args) {
        if (!inThrottle) {
            func.apply(this, args);
            inThrottle = true;
            setTimeout(() => inThrottle = false, limit);
        }
    };
}

// 检查网络连接
function checkNetworkConnection() {
    if (navigator.onLine !== undefined) {
        return navigator.onLine;
    }
    return true; // 默认返回 true
}

// 统一的 API 请求函数
function apiRequest(url, options = {}) {
    const defaultOptions = {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
        },
    };

    const mergedOptions = { ...defaultOptions, ...options };

    return fetch(url, mergedOptions)
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .catch(error => {
            console.error('API请求失败:', error);
            throw error;
        });
}

// 保存到本地存储
function saveToLocalStorage(key, value) {
    try {
        localStorage.setItem(key, JSON.stringify(value));
        return true;
    } catch (error) {
        console.error('保存到本地存储失败:', error);
        return false;
    }
}

// 从本地存储读取
function getFromLocalStorage(key, defaultValue = null) {
    try {
        const item = localStorage.getItem(key);
        return item ? JSON.parse(item) : defaultValue;
    } catch (error) {
        console.error('从本地存储读取失败:', error);
        return defaultValue;
    }
}

// 导出所有函数
if (typeof module !== 'undefined' && module.exports) {
    module.exports = {
        showToast,
        showLoading,
        hideLoading,
        showError,
        formatDateTime,
        debounce,
        throttle,
        checkNetworkConnection,
        apiRequest,
        saveToLocalStorage,
        getFromLocalStorage
    };
}

